import { VideoState } from '@renderer/enums/settingEnum'
import { useSettingsStoreHook } from '@renderer/store'

const isRun = ref(false)

export default () => {
  const { ipc } = window
  const settingsStore = useSettingsStoreHook()
  // 当前正在转换的文件数量
  const convertingCount = ref(0)

  const validate = (): boolean => {
    if (settingsStore.files.length === 0) {
      alert('请选择文件')
      return false
    }

    for (const file of settingsStore.files) {
      try {
        // 检查文件路径是否存在
        if (!file.path) {
          alert('文件路径无效')
          return false
        }

        // 检查输出路径是否有效
        if (!settingsStore.outSavePath) {
          alert('请选择输出路径')
          return false
        }
        // 检查文件是否已经在转换中
        if (file.state === VideoState.CONVERTING) {
          alert('文件已经在转换中')
          return false
        }
      } catch (error) {
        alert(`未知错误: ${error}`)
        return false
      }
    }
    return true
  }

  const progressNotice = () => {
    // 定义进度事件监听器
    const progressListener = (progressData) => {
      settingsStore.files.map((file) => {
        if (file.path === progressData.path && progressData.percent >= 0) {
          file.progress = progressData.percent
        }
      })
    }

    // 定义转换完成事件监听器
    const conversionCompleteListener = (data) => {
      if (data.path !== undefined && data.success) {
        isRun.value = false
        settingsStore.transformComplete(data.path)
        // 当任务列表中的所有任务都完成后
        if (settingsStore.files.every((file) => file.state === VideoState.SUCCESS)) {
          const notify = new Notification('转换完成', {
            icon: '/public/icon.png',
            body: `${settingsStore.files[0].name}等所有视频已转换完成`
          })
          notify.onclick = () => {
            notify.close()
          }
          notify.onclose = () => {
            settingsStore.clearFiles()
          }
          settingsStore.clearFiles()
        }
      }
    }

    // 监听进度事件
    ipc.video.onProgress(progressListener)

    // 监听转换完成事件
    ipc.video.onConversionComplete(conversionCompleteListener)

    // 在组件卸载时移除事件监听器
    onUnmounted(() => {
      ipc.video.removeConversionCompleteListener(conversionCompleteListener)
    })
  }

  const run = () => {
    if (isRun.value) return
    const validateResult = validate()
    if (validateResult) {
      isRun.value = true
      convert()
    }
  }

  const convert = async () => {
    // 获取最大同时转换数量
    const maxCount = settingsStore.maxProcessCount

    // 把所有的准备的任务转换成等待
    settingsStore.files.map((file) => {
      if (file.state === VideoState.READY) file.state = VideoState.PENDING
    })

    // 找到所有等待转换的文件
    const pendingFiles = settingsStore.files.filter((file) => file.state === VideoState.PENDING)

    // 计算可以启动的转换任务数量
    const availableSlots = maxCount - convertingCount.value
    const filesToConvert = pendingFiles.slice(0, availableSlots)

    // 启动转换任务
    filesToConvert.forEach((file) => {
      if (file.state === VideoState.PENDING) {
        // 如果是等待状态，开始转换
        file.state = VideoState.CONVERTING
        convertingCount.value++
        startConversion(file)
      }
    })
  }

  const startConversion = async (file) => {
    try {
      const options = {
        name: file.name,
        inputPath: file.path,
        outputPath: settingsStore.outSavePath,
        format: settingsStore.defaultFormat,
        resolution: settingsStore.resolution,
        bitrate: settingsStore.bitrate,
        framerate: settingsStore.framerate,
        audioQuality: settingsStore.audioQuality,
        videoCodec: settingsStore.videoCodec
      }

      await ipc.video.convert(options)
    } catch (error) {
      console.log('转换失败:', error)
      file.state = VideoState.FAILED
    } finally {
      convertingCount.value--
      // 检查是否有更多文件需要转换
      if (settingsStore.files.some((f) => f.state === VideoState.PENDING)) {
        convert()
      }
    }
  }

  return {
    convert,
    run,
    isRun,
    progressNotice
  }
}
